<?php
namespace app\common\service;

use app\common\model\OrderModel;
use GuzzleHttp\Exception\RequestException;

//活动
class Asiabill
{

    public static function backMoney(OrderModel $order_model,$money)
    {
        $url = Config::pay_asiabill('debug')?'https://api.asiabill.com/servlet/ApplyRefund/V2':'https://api.asiabill.com/servlet/ApplyRefund/V2';
        $data = [
            'merNo'=>Config::pay_asiabill('mer_no'),
            'gateway_no'=>Config::pay_asiabill('gateway_no'),
            'tradeNo'=>$order_model['no'],
            'refundType'=>2,
            'tradeAmount'=>(string)$order_model['pay_money'],
            'refundAmount'=>(string)$money,
            'currency'=>MaBangErp::CURRENCY,
            'refundReason'=>"",
        ];
        $data['signInfo'] = self::getSign($data['merNo'].$data['gateway_no'].$data['tradeNo'].$data['currency'].$data['refundAmount']);
        $result = self::req($url, $data);
        if(is_array($result)){
            if(isset($result['applyRefund'])){
                $applyRefund = $result['applyRefund'];
                $state = 0;
                if($applyRefund['code']=='00'){
                    $state = 1;
                }elseif($applyRefund['code']=='110'){
                    $state = 2 ;
                }
                return [$applyRefund['code'],$state,$applyRefund['description'],json_encode($applyRefund)];
            }else{
                return [null,0,'',json_encode($result)];
            }
        }else{
            return [0,0,'',$result];
        }
    }

    public static function getSign($str)
    {
        $signkey = Config::pay_asiabill('sign_key');
        $signInfo=hash("sha256",$str.$signkey);
        return $signInfo;
    }

    public static function req($url,$data,$method="POST",array $headers = []){
        try{
            $client = new \GuzzleHttp\Client();
            $options = [
                'form_params'=>$data,
                'verify'=>false,
                'headers' => !empty($headers)?$headers:[
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ]
            ];

            $response = $client->request($method, $url, $options);
            $result = $response->getBody()->getContents(); // '{"id": 1420053, "name": "guzzle", ...}'
            return xml_to_array($result);
        }catch (RequestException $e){
            $result = $e->getResponse()->getBody()->getContents();
        }catch (\Exception $e){
            $result = "{'errmsg':'{$e->getmessage()}'}";
        }


    }

}